import { login, getInfo, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  // name: '',
  // avatar: '',
  // introduction: '',
  // roles: []
  name: '',
  userName: '',
  userId: '',
  email: '',
  mobile: '',
  avatar:
    'https://img0.baidu.com/it/u=2241125531,1294094674&fm=26&fmt=auto&gp=0.jpg',
  introduction: 'hhhh',
  roles: ['admin'],
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_EMAIL: (state, email) => {
    state.name = email
  },
  SET_MOBILE: (state, mobile) => {
    state.name = mobile
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
    localStorage.setItem('userId', userId)
  },
  SET_USERNAME: (state, userName) => {
    state.userName = userName
    localStorage.setItem('userName', userName)
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, captcha, uuid } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, captcha, uuid })
        .then((res) => {
          commit('SET_TOKEN', res.token)
          commit('SET_NAME', res.body.username)
          commit('SET_USERNAME', res.body.username)
          commit('SET_USERID', res.body.userId)
          commit('SET_EMAIL', res.body.email)
          commit('SET_MOBILE', res.body.mobile)
          setToken(res.token)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // get user info  暂未用
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          const { data } = response

          if (!data) {
            reject('Verification failed, please Login again.')
          }

          const { roles, name, avatar, introduction } = data

          // roles must be a non-empty array
          if (!roles || roles.length <= 0) {
            reject('getInfo: roles must be a non-null array!')
          }

          commit('SET_ROLES', roles)
          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
          commit('SET_INTRODUCTION', introduction)

          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_NAME', '')
      commit('SET_USERID', '')
      commit('SET_USERNAME', '')
      commit('SET_EMAIL', '')
      commit('SET_MOBILE', '')
      commit('SET_ROLES', [])
      removeToken()
      resetRouter()
      resolve()
      // logout(state.token).then(() => {
      //   commit('SET_TOKEN', '')
      //   commit('SET_NAME', '')
      //   commit('SET_USERID', '')
      //   commit('SET_EMAIL', '')
      //   commit('SET_MOBILE', '')
      //   commit('SET_ROLES', [])
      //   removeToken()
      //   resetRouter()
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, {
      root: true,
    }) // 路由权限
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
